package com.zmkj.cn.sys.service.impl;

import com.zmkj.cn.comm.constant.RedisConstant;
import com.zmkj.cn.comm.constant.ResultCode;
import com.zmkj.cn.comm.exception.BaseException;
import com.zmkj.cn.comm.vo.CommonResultVo;
import com.zmkj.cn.sys.constant.LoginPortConstant;
import com.zmkj.cn.sys.constant.WechatConstant;
import com.zmkj.cn.sys.service.IUploadService;
import com.zmkj.cn.sys.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 上传
 *
 * @author 伍绍宇
 * @date 2021/06/04
 */
@Service
@Slf4j
public class UploadServiceImpl implements IUploadService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public Object upload(MultipartFile file, HttpServletRequest request) {
        String url = "";
        var valid = valid(request);
        if (valid.getCode() != 0) {
            return valid;
        } else {
            url = valid.getBody().toString();
        }
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.MULTIPART_FORM_DATA);
        header.add(WechatConstant.TOKEN.value, request.getHeader(WechatConstant.TOKEN.value));
        header.add(WechatConstant.LOGIN_PORT.value, LoginPortConstant.WECHAT.value + "");
        HttpHeaders fileHeader = new HttpHeaders();
        fileHeader.setContentType(MediaType.parseMediaType(file.getContentType()));
        fileHeader.setContentDispositionFormData("file", file.getOriginalFilename());
        Map result = null;
        try {
            HttpEntity<ByteArrayResource> fileEntity = new HttpEntity<>(new ByteArrayResource(file.getBytes()),
                    fileHeader);
            multiValueMap.add("file", fileEntity);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, header);
            ResponseEntity<Map> postForEntity = restTemplate.postForEntity(url, httpEntity, Map.class);
            result = postForEntity.getBody();
        } catch (Exception e) {
            log.info("上传失败" + e);
        }
        return result;
    }
    @Resource
    private RedisUtil redisUtil;

    private CommonResultVo valid(HttpServletRequest request) {
        log.info("upload file,hospital:{}",request.getParameter("hospitalId"));
        // 获取URL
        String url = request.getServletPath();
        // 过滤未传递token数据
        String token = request.getHeader(WechatConstant.TOKEN.value);
        if (token == null) {
            if(request.getParameter("hospitalId") != null){

                Object map = redisUtil.getMap(RedisConstant.HOSPITAL_INFO.value, request.getParameter("hospitalId"));
                if (map == null) {
                    // 找不到对应医院
                    return CommonResultVo.failed(ResultCode.HOSPITAL_ERROR);
                }
                String hospitalInfo = map.toString();
                String forwardUrl = hospitalInfo + url;
                return CommonResultVo.success(forwardUrl);
            }
            return CommonResultVo.failed(ResultCode.NOT_HAVE_TOKEN);
        }else {

            Object hospitalKey = redisUtil.get(token);
            if (hospitalKey == null) {
                // token失效
                return CommonResultVo.failed(ResultCode.UNAUTHORIZED);
            }
            Object map = redisUtil.getMap(RedisConstant.HOSPITAL_INFO.value, hospitalKey.toString());
            if (map == null) {
                // 找不到对应医院
                return CommonResultVo.failed(ResultCode.HOSPITAL_ERROR);
            }
            String hospitalInfo = map.toString();
            String forwardUrl = hospitalInfo + url;
            return CommonResultVo.success(forwardUrl);
        }

    }
}
